package com.kfm.storage.Receiver;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.file.Files;
import java.nio.file.Path;

/**
 * @author Aurora雪
 */

/**
 * 文件接收类
 */
public class FileReceiver {
    public static void fileReceiver(String saveFolderPath, int port) {
        // 创建ServerSocket对象并监听指定端口
        try (ServerSocket serverSocket = new ServerSocket(port)) {
            System.out.println("等待接收文件...");

            while (true) {
                // 等待客户端连接
                Socket socket = serverSocket.accept();
                System.out.println("等待客户端连接...");

                // 创建文件输出流
                DataInputStream dataInputStream = new DataInputStream(socket.getInputStream());
                String requestIdentifier = dataInputStream.readUTF();
                String fileName = dataInputStream.readUTF();
                String fileExtension = dataInputStream.readUTF();
                String fullFileName = fileName + "." + fileExtension;
                File outputFile = new File(saveFolderPath, fullFileName);

                // 处理删除文件的请求
                if (requestIdentifier.contains("delete")) {
                    if (outputFile.exists()) {
                        outputFile.delete();
                        System.out.println("删除文件完成：" + fullFileName);
                    } else {
                        System.out.println("文件不存在：" + fullFileName);
                    }
                    continue;
                }

                // 获取Socket的输入流
                InputStream inputStream = socket.getInputStream();

                // 读取文件字节流并保存到文件中
                byte[] buffer = new byte[1024];
                int bytesRead;
                while ((bytesRead = inputStream.read(buffer)) != -1) {
                    outputFile.createNewFile(); // 如果文件不存在，创建新文件
                    FileOutputStream fileOutputStream = new FileOutputStream(outputFile, true); // 追加写入模式
                    fileOutputStream.write(buffer, 0, bytesRead);
                    fileOutputStream.close();
                }

                // 关闭文件输出流和Socket连接
                socket.close();

                System.out.println("文件接收完成：" + fileName);
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}